﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml.Linq;
using System.Collections.ObjectModel;

namespace AcctrueWMS.Foundation.WebControls
{
    public class AccTree : AccControl
    { 
        class Node
        {
            public string Key;
            public string Name;
            public string Value;
            public string Text;
            public string WBS;
            public Collection<Node> Childs = new Collection<Node>();
        }
        
        public AccTree()
        {
        }
        private string GetCellValue(string name, DataRow row)
        {
            if (row.Table.Columns.Contains(name))
                return row[name].ToString();
            else
                return string.Empty;
        }

        private void BuildTree(Node node, DataView dv)
        {
            DataRow[] rows = FindChildRows(dv, node.WBS);
            foreach (DataRow row in rows)
            {
                Node child = new Node();
                child.Key=GetCellValue("key",row);
                child.Name=GetCellValue("name",row);
                child.Text=GetCellValue("text",row);
                child.Value = GetCellValue("value", row);//value              

                child.WBS = row["wbsCode"].ToString();
                node.Childs.Add(child);
                BuildTree(child, dv);
            }
        }

        private DataRow[] FindChildRows(DataView dv, string wbs)
        {          
            int level = Count(wbs, '.');
            Collection<DataRow> result = new Collection<DataRow>();
            if (string.IsNullOrEmpty(wbs))
            {
                dv.RowFilter = "wbsCode not like '%.%'";
                for (int i = 0; i < dv.Count;i++ )
                {
                    result.Add(dv[i].Row);
                }
            }
            else
            {
                dv.RowFilter=string.Format("wbsCode like '{0}.%'", wbs);
                for(int i=0;i<dv.Count;i++)
                {
                    DataRowView row = dv[i];
                    if (Count(row["wbsCode"].ToString(), '.') == level + 1)
                    {
                        result.Add(row.Row);
                    }
                }
            }
            return result.ToArray();
        }


        private int Count(string str, char op)
        {
            if (string.IsNullOrEmpty(str))
                return 0;

            int index = -1;
            int cnt = 0;
            while ((index = str.IndexOf(op, index + 1)) > -1)
            {
                cnt++;
            }
            return cnt;
        }

        public bool Checkable
        {
            get;
            set;
        }

        private void NodeToString(Node node,StringBuilder sb)
        {
            sb.Append(string.Format("{{ name:\"{0}\",key:\"{1}\",value:\"{2}\",wbs:\"{3}\",text:\"{4}\"",node.Name,node.Key,node.Value,node.WBS,node.Text));
            if (node.Childs.Count > 0)
            {
                sb.Append(", nodes: [ ");
                for (int i = 0; i < node.Childs.Count; i++)
                {
                    NodeToString(node.Childs[i],sb);
                    if (i < node.Childs.Count - 1)
                        sb.Append(",");
                }
                sb.Append("]");
            }
            sb.Append("}");
        }
        #region 返回绑定树形结构数据源

        //private const string script_format = "var wmsTree_{0}; var setting_{0} = {expandSpeed: \"\", showLine: true ,callback : {click: wmsTreeOnClick }}; wmsTree_{0} = $(\"#wmsTreeCtl_{0}\").zTree(setting_{0}, wmsTree_data_{0});";
        private const string html_fotmat = "<div class=\"zTreeDemoBackground\"><ul id=\"wmsTreeCtl_{0}\" class=\"tree\"></ul></div>";
        public override string Render()
        {
            StringBuilder sb = new StringBuilder();
            
            sb.Append(string.Format(html_fotmat,Name));
            sb.Append("<script type=\"text/javascript\">");
            sb.Append(string.Format(" var wmsTree_data_{0} = [",Name));

            DataTable dt = DataSource as DataTable;
            DataView dv = dt.DefaultView;
            dv.Sort = " wbsCode asc ";
            
            Node root = new Node();
            BuildTree(root, dv);
            for (int i = 0; i < root.Childs.Count(); i++)
            {
                NodeToString(root.Childs[i],sb);
                if (i < root.Childs.Count - 1)
                    sb.Append(",");
            }
            sb.Append("];" );
            sb.Append(string.Format("var wmsTree_{0};", Name));          
            sb.Append(string.Format("var setting_{0} = {{expandSpeed: \"\", showLine: true ,checkable:{1},callback : {{click: wmsTreeOnClick,change: zTreeOnChange }}}};", Name, Checkable.ToString().ToLower()));           
            sb.Append(string.Format(" wmsTree_{0} = $(\"#wmsTreeCtl_{0}\").zTree(setting_{0}, wmsTree_data_{0});",Name));
            sb.Append("</script>");
            return sb.ToString();
        }
        #endregion
    }
}